package com.flycms.web.front.rest;

import com.flycms.constant.StatusConst;
import com.flycms.core.base.BaseController;
import com.flycms.core.entity.DataVo;
import com.flycms.core.entity.PageVo;
import com.flycms.core.entity.RestDataVo;
import com.flycms.module.article.model.Article;
import com.flycms.module.article.model.ArticleCategory;
import com.flycms.module.article.model.ArticleVotes;
import com.flycms.module.article.service.ArticleCategoryRestService;
import com.flycms.module.article.service.ArticleRestService;
import com.flycms.module.comment.model.OptionCount;
import com.flycms.module.comment.service.CollectsService;
import com.flycms.module.other.service.FilterKeywordService;
import com.flycms.module.user.model.User;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.flycms.module.comment.model.FlyContentType.ARTICLE;
import static com.flycms.constant.StatusConst.*;

/**
 * 开发公司：宏石<br/>
 * 版权：宏石<br/>
 *
 * @author sun-kaifei
 * @version 1.0 <br/>
 * @email xxx@qq.com
 * @Date: 19:77 2020/9/17
 */
@RestController
@RequestMapping(value = "/rest/article")
public class ArticleRestController extends BaseController {
    @Autowired
    protected ArticleRestService articleService;
    @Autowired
    protected FilterKeywordService filterKeywordService;
    @Autowired
    protected ArticleCategoryRestService articleCategoryService;
    @Autowired
    protected CollectsService collectsService;

    /**
     * 文章分类列表
     *
     * @param id
     * @return
     */
    @GetMapping(value = {"/ac/index", "/ac/{id}"})
    public RestDataVo getArticleList(@PathVariable(value = "id", required = false) String id) {
        ArticleCategory category;
        List<Map<String, Object>> tree;
        List<ArticleCategory> categoryList = articleCategoryService.getCategoryAllList();
        if (id != null) {
            if (!NumberUtils.isNumber(id)) {
                return RestDataVo.ERROR("传入参数非整形，查询文章分类列表失败！");
            }
            category = articleCategoryService.findCategoryById(Long.parseLong(id), 2);
            if (category == null) {
                return RestDataVo.ERROR("不存在该分类！");
            }
            tree = ArticleCategoryRestService.queryItemListByTmpl(categoryList, Long.parseLong(id));
        } else {
            tree = ArticleCategoryRestService.queryItemListByTmpl(categoryList, 0L);
        }
        return RestDataVo.OK("查询成功", categoryList);
    }

    /**
     * 文章列表
     *
     * @return
     */
    @GetMapping(value = "/list")
    public RestDataVo getArticleList(@RequestParam(value = "pageIndex", required = false) String pageIndex,
                                     @RequestParam(value = "pageSize", required = false) String pageSize,
                                     @RequestParam(value = "title", required = false) String title,
                                     @RequestParam(value = "status", required = false) Integer status,
                                     @RequestParam(value = "userId", required = false) Long userId,
                                     @RequestParam(value = "typeId", required = false) Long typeId,
                                     @RequestParam(value = "recommend", required = false) Integer recommend) {
        if (!NumberUtils.isNumber(pageIndex)) {
            pageIndex = "1";
        }
        if (!NumberUtils.isNumber(pageSize)) {
            pageSize = "5";
        }
        if (status != null && status == 3) {
            return RestDataVo.ERROR("查询文章的状态参数错误，查询文章列表失败！");
        } else if (status == null) {
            status = 1;
        }
        String orderby = null;
        if (recommend != null) {
            orderby = "recommend";
        }
        PageVo<Article> page = articleService.getArticleListPage(title, userId, typeId, null, status, orderby, null, Integer.parseInt(pageIndex), Integer.parseInt(pageSize));
        return RestDataVo.PAGE(page.getList(), Integer.parseInt(pageIndex), Integer.parseInt(pageSize), page.getCount());
    }

    /**
     * 文章列表
     *
     * @param
     * @return
     */
    @GetMapping(value = "/list/hot")
    public RestDataVo getHotArticleList() {
        List<Article> hotArticle = articleService.findHotArticleByCountView();
        return RestDataVo.PAGE(hotArticle, 1, 5, hotArticle.size());
    }

    @GetMapping(value = "/list/cognate")
    public RestDataVo getCognateArticleList(@RequestParam(value = "typeId") String typeId) {
        List<Article> list = articleService.getCognateArticleList(typeId);
        return RestDataVo.PAGE(list, 1, 5, list.size());
    }


    //文章详细页面
    @GetMapping(value = {"/shortUrl={shortUrl}", "/{id}"})
    public RestDataVo getArticleById(@PathVariable(value = "shortUrl", required = false) String shortUrl,
                                     @PathVariable(value = "id", required = false) Long id)  throws Exception{
        Article article;
        if (id != null) {
            article = articleService.findArticleById(id, 9);
        } else if (!StringUtils.isBlank(shortUrl)) {
            //查询文章内容信息，由于缓存问题，统计要实时更新，所以统计和内容分开查询
            article = articleService.findArticleByShorturl(shortUrl, null);
        } else {
            return RestDataVo.ERROR("参数错误，接口访问失败");
        }
        if (article == null) {
            return RestDataVo.ERROR("文章不存在");
        }

        if (getAdminUserId() != null) {
            if (article.getStatus().equals(NOUSE.value())) {
                return RestDataVo.ERROR("暂时不能查看未提交审核的草稿");
            }
        } else {
            if (article.getStatus().equals(LOCKED.value())
                    || article.getStatus().equals(DELETE.value())
                    || article.getStatus().equals(CLOSE.value())) {
                return RestDataVo.ERROR("文章已被删除或锁定，无法查看");
            }
            if (article.getStatus().equals(NOUSE.value())
                    || article.getStatus().equals(TO_AUDIT.value())) {
                if (!article.getUserId().equals(getUserId())) {
                    return RestDataVo.ERROR("只能查看自己的草稿或未审核的文章");
                }
            }
        }
        //违禁词过滤
        article.setTitle(filterKeywordService.doFilter(article.getTitle()));
        article.setContent(filterKeywordService.doFilter(article.getContent()));
        User user = userService.findUserById(article.getUserId(), 1);
        if (user == null) {
            article.setUserName("账号已注销或封禁");
        } else {
            if (user.getUserName() == null || "".equals(user.getUserName())) {
                article.setUserName("用户" + article.getUserId());
            } else {
                article.setUserName(user.getUserName());
            }
        }
        String name = articleCategoryService.findCategoryById(article.getTypeId(), 1).getName();
        article.setTags(name);
        //查询统计信息（暂用）
        OptionCount count = articleService.queryCountById(article.getId());
        int collectCount = collectsService.getCollectCount(null, article.getId(), ARTICLE);
        if (count != null) {
            article.setCountDigg(count.getUpCount());
            article.setCountBurys(count.getDownCount());
            article.setCountView(count.getBrowsedCount());
            article.setCountComment(count.getCommentCount());
            article.setCollectCount(collectCount);
        } else {
            article.setCountDigg(0);
            article.setCountBurys(0);
            article.setCountView(0);
            article.setCountComment(0);
        }

        return RestDataVo.OK("查询文章详情成功", article);
    }

    //文章详细内容
    @ResponseBody
    @RequestMapping(value = "/findArticleById/{id}")
    public RestDataVo findArticleById(@PathVariable(value = "id", required = false) String id) {
        if (!NumberUtils.isNumber(id)) {
            return RestDataVo.ERROR("id参数错误");
        }
        Article article = articleService.findArticleById(Long.parseLong(id), 2);
        if (article == null) {
            return RestDataVo.ERROR("该内容不存在或者未审核！");
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("content", article.getContent());
        return RestDataVo.OK("查询文章详情成功", map);
    }


    //保存添加文章
    @PostMapping("/u/article_save")
    @ResponseBody
    public RestDataVo addAdminSave(@RequestBody @Valid Article article, BindingResult result) {
        RestDataVo data;
        try {
            if (result.hasErrors()) {
                List<ObjectError> list = result.getAllErrors();
                for (ObjectError error : list) {
                    return RestDataVo.ERROR(error.getDefaultMessage());
                }
                return null;
            }
            if (article.getStatus() != null && article.getStatus() != -1) {
                article.setStatus(null);
            }
            article.setUserId(getUser().getUserId());
            data = articleService.addArticle(article);
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }


    /**
     * 保存修改文章
     *
     * @param article
     * @param result
     * @return RestDataVo
     */
    @PostMapping("/u/article_update")
    @ResponseBody
    public RestDataVo editArticleById(@RequestBody @Valid Article article, BindingResult result) {
        RestDataVo data;
        try {
            if (result.hasErrors()) {
                List<ObjectError> list = result.getAllErrors();
                for (ObjectError error : list) {
                    return RestDataVo.ERROR(error.getDefaultMessage());
                }
                return null;
            }
            Article info = articleService.findArticleById(article.getId(), 9);
            if (info == null) {
                return RestDataVo.ERROR("该内容不存在,或已被管理员锁定");
            }
            if (!getUser().getUserId().equals(info.getUserId())) {
                return RestDataVo.ERROR("只能修改属于自己的文章！");
            }
            article.setUserId(getUser().getUserId());
            article.setShortUrl(info.getShortUrl());
            data = articleService.editArticleById(article);
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }

    //按父级id查询id下所有分类列表
    @ResponseBody
    @RequestMapping(value = "/u/article/category_child")
    public DataVo getCategoryChildList(@RequestParam(value = "parentId", defaultValue = "0") Long parentId) {
        List<ArticleCategory> list = articleCategoryService.getCategoryListByFatherId(parentId);
        return DataVo.success("查询指定分类列表成功", list);
    }

    /**
     * 文章浏览量更新
     *
     * @param id
     * @return RestDataVo
     */
    @ResponseBody
    @GetMapping(value = "/viewcount/{id}")
    public RestDataVo updateArticleByViewCount(@PathVariable(value = "id", required = false) String id) {
        RestDataVo data = RestDataVo.OK("操作成功");
        try {
            if (!NumberUtils.isNumber(id)) {
                return RestDataVo.ERROR("文章参数错误");
            }
            articleService.updateArticleViewCount(Long.parseLong(id));
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }


    /**
     * 处理喜欢操作
     *
     * @param id
     * @param type
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/article/digg/{id}/{type}")
    public RestDataVo articleDigg(@PathVariable(value = "id", required = false) String id,
                                  @PathVariable(value = "type", required = false) String type) {
        RestDataVo data;
        try {
            if (!StringUtils.isBlank(id)) {
                if (!NumberUtils.isNumber(id)) {
                    return RestDataVo.ERROR("id参数错误");
                }
            } else {
                return RestDataVo.ERROR("ID不能为空！");
            }
            if (!StringUtils.isBlank(type)) {
                if (!NumberUtils.isNumber(type)) {
                    return RestDataVo.ERROR("信息类型参数错误");
                }
            } else {
                return RestDataVo.ERROR("信息类型不能为空！");
            }
            if (getUser() == null) {
                return RestDataVo.ERROR("请登陆后再喜欢");
            }
            ArticleVotes articleVotes = new ArticleVotes();
            articleVotes.setInfoType(Integer.valueOf(type));
            articleVotes.setUserId(getUser().getUserId());
            articleVotes.setInfoId(Long.parseLong(id));
            articleVotes.setDigg(1);
            data = articleService.updateArticleVotesById(articleVotes);
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }

    /**
     * 删除文章
     *
     * @param id
     * @return RestDataVo
     */
    @PostMapping(value = {"/u/del/{id}", "/u/del/{id}/{rel}"})
    @ResponseBody
    public RestDataVo deleteArticleById(@PathVariable(value = "id") Long id,
                                        @PathVariable(value = "rel", required = false) Integer rel) {
        RestDataVo data;
        User user = getUser();
        Integer status = rel == null ? 1 : rel;
        Article article = articleService.findArticleById(id, status);
        if (article == null) {
            return RestDataVo.ERROR("不存在该文章");
        }
        if (user.getUserId().equals(article.getUserId())) {
            return RestDataVo.ERROR("只能删除属于自己的文章");
        }

        data = articleService.deleteArticleById(id);
        return data;
    }


}
